﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace coreEntityFramework.Extend.attrible
{
    public class ValidParameterAttribute : IAsyncActionFilter
    {

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
           

            if (!context.ModelState.IsValid)
            {
                var errors = context.ModelState.Values.Select(x => x.Errors);
                List<string> errormsg = new List<string>();
                foreach (var item in errors)
                {
                    for (int i = 0; i < item.Count; i++)
                    {
                        errormsg.Add(item[i].ErrorMessage);
                    }

                }
                var response = new HttpResponseMessage();
                response.Content = new StringContent(string.Join("\n", errormsg.ToArray()));
                response.StatusCode = HttpStatusCode.BadRequest;

                // actionContext.HttpContext.Response.
                await HandleExceptionAsync(context.HttpContext, context.HttpContext.Response.StatusCode, string.Join("\n", errormsg.ToArray()));


            }
            else
            {
                await next();
            }
        }


        private static Task HandleExceptionAsync(HttpContext context, int statusCode, string msg)
        {
            var data = new { status = statusCode, is_success = false, msg = msg };
            var result = JsonConvert.SerializeObject(new { data = data });
            context.Response.ContentType = "application/json;charset=utf-8";
            return context.Response.WriteAsync(result);
        }

    }
}
